package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.CustomException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import com.itheima.ydd.vo.CateVo;
import com.itheima.ydd.vo.UserVo;
import com.itheima.ydd.vo.YddArticleVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddArticleService yddArticleService;

    @Autowired
    private YddAdvposService yddAdvposService;

    @Autowired
    private YddAdvimgService yddAdvimgService;

    @Autowired
    private YddTagService yddTagService;

    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private YddUserDataService yddUserDataService;

    @GetMapping("/baseInfo")
    public Result baseInfo() {
        Map map = new HashMap();
        //获取新闻总类
        List<CateVo> cateVoList = new ArrayList<>();
        //获取分类
        List<YddCate> yddCateList = yddCateService.list();
        for (YddCate yddCate : yddCateList) {
            CateVo cateVo = new CateVo();
            cateVo.setId(yddCate.getId());
            cateVo.setCatename(yddCate.getCatename());
            //获取分类对应文章查询条件
            LambdaQueryWrapper<YddArticle> yaQueryWrapper = new LambdaQueryWrapper<>();
            yaQueryWrapper.eq(YddArticle::getCateid, yddCate.getId());
            int count = yddArticleService.count(yaQueryWrapper);
            cateVo.setNum(count);
            cateVoList.add(cateVo);
        }
        map.put("all_cate", cateVoList);
        //获取广告位总数
        map.put("advpos_num", yddAdvposService.count());
        //获取标签总数
        map.put("tag_num", yddTagService.count());
        //获取管理者总数
        map.put("admin_num", sysUserService.count());
        //获取文章总数
        map.put("article_num", yddArticleService.count());
        //获取分类总数
        map.put("cate_num", yddCateService.count());
        //获取广告图片总数
        map.put("advimg_num", yddAdvimgService.count());
        //获取最新用户数
        //构造用户查询条件
        LambdaQueryWrapper<YddUser> yuQueryWrapper = new LambdaQueryWrapper<>();
        yuQueryWrapper.orderByDesc(YddUser::getId);
        yuQueryWrapper.last("limit 7");
        List<YddUser> yddUserList = yddUserService.list(yuQueryWrapper);
        map.put("new_user", yddUserList);
        //获取热点文章
        //构造热点文章查询条件
        LambdaQueryWrapper<YddArticle> yaQueryWrapper = new LambdaQueryWrapper<>();
        yaQueryWrapper.orderByDesc(YddArticle::getClick);
        yaQueryWrapper.last("limit 7");
        List<YddArticle> yddArticleList = yddArticleService.list(yaQueryWrapper);
        map.put("hot_article", yddArticleList);
        //获取用户总人数
        UserVo userVo = new UserVo();
        int yucount = yddUserService.count();
        //构造分页条件获得男生总数
        LambdaQueryWrapper<YddUser> yQueryWrapper = new LambdaQueryWrapper<>();
        yQueryWrapper.eq(YddUser::getSex, 1);
        int mancount = yddUserService.count(yQueryWrapper);
        userVo.setTotal(yucount);
        userVo.setUser_man(mancount);
        userVo.setUser_woman(yucount - mancount);
        map.put("user", userVo);

        return Result.ok("基本页面", map);

    }


    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        log.info("登陆用户：{}", sysUser.toString());

        String loginName = sysUser.getLogin_name();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLogin_name, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        } else if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRole_id()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }

    @GetMapping("/getConfig")
    public R systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTab_value, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttr_key(), sysConfig.getAttr_value());
        }

        return new R(map, "", 0);

    }

    @PostMapping("/profile")
    public R profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
        Long userId = Long.valueOf((String) claims.get("userId"));

        log.info("用户id:{}", userId);
        return sysUserService.profile(userId);
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    //文章详情数据
    @GetMapping("/show")
    public Result show(String id) {
        Map<String, Object> res = new HashMap<>();

        //查询上一篇文章数据
        LambdaQueryWrapper<YddArticle> pqw = new LambdaQueryWrapper<>();
        int prev = Integer.parseInt(id) - 1;

        pqw.eq(YddArticle::getId, prev);
        pqw.select(YddArticle::getId, YddArticle::getTitle);
        YddArticle prevArticle = yddArticleService.getOne(pqw);

        if (prevArticle == null) {
            throw new CustomException("没有上一篇了");
        }
        res.put("prev", prevArticle);

        //查询下一篇文章数据
        LambdaQueryWrapper<YddArticle> nqw = new LambdaQueryWrapper<>();
        int next = Integer.parseInt(id) + 1;
        nqw.eq(YddArticle::getId, next);
        nqw.select(YddArticle::getId, YddArticle::getTitle);
        YddArticle nextArticle = yddArticleService.getOne(pqw);

        if (nextArticle == null) {
            throw new CustomException("没有下一篇了");
        }
        res.put("next", nextArticle);


        //查询info数据
        //先查文章基本信息
        LambdaQueryWrapper<YddArticle> articleLqw = new LambdaQueryWrapper<>();
        articleLqw.eq(YddArticle::getId, id);
        YddArticle article = yddArticleService.getOne(articleLqw);
        //创建vo对象
        YddArticleVo yddArticleVo = new YddArticleVo();
        BeanUtils.copyProperties(article, yddArticleVo);
        //查询对应的分类名称catename
        LambdaQueryWrapper<YddCate> cateLqw = new LambdaQueryWrapper<>();
        cateLqw.eq(YddCate::getId, article.getCateid());
        YddCate yddCate = yddCateService.getOne(cateLqw);
        String catename = yddCate.getCatename();
        yddArticleVo.setCatename(catename);

        //查询是否点赞和是否收藏
        LambdaQueryWrapper<YddUserData> userDataLqw = new LambdaQueryWrapper<>();
        //根据当前文章的用户id来查询表ydduserdata表
        userDataLqw.eq(YddUserData::getUser_id, article.getUser_id());
        List<YddUserData> userDatas = yddUserDataService.list(userDataLqw);

        for (YddUserData userData : userDatas) {
            Integer type = userData.getType();
            if (type == 1) {
                yddArticleVo.setIsCollect(true);
                yddArticleVo.setIsLike(false);
            } else {
                yddArticleVo.setIsCollect(false);
                yddArticleVo.setIsLike(true);
            }
        }
        res.put("info", yddArticleVo);

        //查询推荐文章数据
        Page<YddArticle> page = new Page<>(1, 8);

        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getCateid, yddArticleVo.getCateid());
        lqw.eq(YddArticle::getIshot, 1);
        lqw.select(YddArticle::getId, YddArticle::getCateid, YddArticle::getTitle, YddArticle::getPic);
        //根据cateid查询八个
        yddArticleService.page(page, lqw);
        List<YddArticleVo> recommend = page.getRecords().stream().map(s -> {
            YddArticleVo yddArticleVo1 = new YddArticleVo();
            YddCate cate = yddCateService.getById(s.getCateid());
            BeanUtils.copyProperties(s, yddArticleVo1);
            yddArticleVo1.setCatename(cate.getCatename());
            return yddArticleVo1;
        }).collect(Collectors.toList());

        res.put("recommend", recommend);

        return Result.ok("", res);
    }

}
